'''
parse_ff
Parse friends and followers of a person
Attention:
    Followers and friends should be insert into database with it's prior ordering.
    Ordering is important because it represents the timeline of a person's evolution.
    Such as A's friends order is B->C->D, so B is prior than C and D.
'''
from BeautifulSoup import BeautifulSoup
import MySQLdb
import time
import database_connector
import User
import Relation

'''
There are 2 ways to construct an instance from this class.
You could pass the html to this class directly.
Or you could pass a file name to it if you already saved the page.
'''
class Parse:
    __html = ''
    __file_name = ''
    __database_conn = None
    __dc_flag = True
    __user = User()
    __follower = Follower()
    __friend = Friend()
    __follower_flag = True

    def setFollowerFlag(flag):
	self.__follower_flag = flag

    def setHtml(html):
        self.__html = html

    def setDatabaseConnector(ip, user, passwd, database):
        if self.__dc_flag:
            self.__database_conn = DatabaseConnector(ip, user, passwd, database)
            self.__dc_flag = False
            self.__database_conn.connect()

    def setFileName(fn):
        self.__file_name = fn

    def parseHtmlAndInsert(uid):
        if self.__dc_flag:
            raise
            return
        soup = BeautifulSoup(self.__html)
        for p in soup.findAll('p','name mbspace'):
            self.__user.setLocation(p.span.contents[-1:][0])
            self.__user.setName(p.a.contents[0])
            self.__user.setUid(p.a['usercard'][-10:])
            if x.img['class'] == 'female':
                self.__user.setGender(0)
            else:
                self.__user.setGender(1)
            if len(x.a) == 1:
                self.__user.setVertified(0)
            else:
                self.__user.setVertified(1)
            self.__database_conn.setSql('insert into users(uid, name, location, gender, vertified) values(%s, %s, %s, %d, %d)')
            self.__database_conn.setParam(self.__user.getTuple())
            self.__database_conn.insertOneEntry()
	    if __follower_flag:
		self.__follower.setUid(uid)
		self.__follower.setRUid(p.a['usercard'][-10:])
		self.__database_conn.setSql('insert into followers(uid, follower)values(%s, %s)')
                self.__database_conn.setParam(self.__follower.getTuple())
		self.__database_conn.insertOneEntry()
	    else:
        	self.__friend.setUid(uid)
		self.__friend.setRUid(p.a['usercard'][-10:])
		self.__database_conn.setSql('insert into friends(uid, friend)values(%s, %s)')
                self.__database_conn.setParam(self.__friend.getTuple())
		self.__database_conn.insertOneEntry()
